<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 * 访客
 */
class UserVisit extends Model
{
    protected $table = 'user_visit';

    protected $fillable = [
        'user_id', 'visited_user_id', 'flag'
    ];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 用户userId的访客列表
     */
    static function addRecord($userId = 0, $visitedUserId = 0)
    {
        if (!$userId || !$visitedUserId || $userId == $visitedUserId) return false;
        $info = [
            'user_id' => $userId,
            'visited_user_id' => $visitedUserId,
        ];
        return self::updateOrCreate($info, $info);
    }

    /**
     * 用户userId的访客列表
     */
    static function getList($userId = 0)
    {
        $where = [
            'visited_user_id' => $userId,
            'flag' => 1
        ];
        return self::where($where)->orderBy('id', 'desc')->pluck('user_id')->toArray();
    }

    /**
     * 用户userId的访客数量
     */
    static function getNum($userId = 0)
    {
        $where = [
            'visited_user_id' => $userId,
            'flag' => 1
        ];
        return self::where($where)->count();
    }
}
